<?php

class Front_LoginController extends ExtLb_Controller_Action
{
	private $loginSess;

    public function init()
    {
        /* Initialize action controller here */
    	$this->loginSess = new Zend_Session_Namespace('loginSess');
    	
    }

    public function indexAction()
    {
        // action body
    	if(!Zend_Auth::getInstance()->hasIdentity()){
    		$this->jShowMessage("Hãy đăng nhập trước");
    		
  			$this->_redirect('front/index');
    	}
    }
    
    public function loginAction(){
    	if(isset($_POST['cmdLogin'])){
    		$user = $this->_getParam('txtUser');
    		$pass = md5($this->_getParam('txtPass'));

    		$authAdapter = $this->getAuthAdapter();
    		$authAdapter->setIdentity($user)
    					->setCredential($pass);
    	
    		$auth = Zend_Auth::getInstance();
    		$result = $auth->authenticate($authAdapter);
    		if($result->isValid()){
    			//LAY DU LIEU CAN THIET LUU VAO SESSION KHI DANG NHAP THANH CONG
    			//va loai bo cac field ko dc storage (trong array)
    			$identiy  = $authAdapter->getResultRowObject(NULL,array('password'));
    			$auth->getStorage()->write($identiy);
    			
    			$this->jShowMessage("Đăng nhập thành công!!!");
    			
//    			$this->_forward('index','info','front');
    		}
    	}
    	
    	if(!Zend_Auth::getInstance()->hasIdentity()){
    		$this->_redirect('front/index');
    	}else {
    		if(Zend_Auth::getInstance()->getIdentity()->quyen == "admin"){
    			$this->_redirect('admin/index');	
    		}
    		$this->_redirect('front/info');
    	}
    }
    
    public function logoutAction(){
    	Zend_Auth::getInstance()->clearIdentity();
    	$this->_redirect('front/index');
    }
    
    
    
    private function getAuthAdapter(){
    	$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
    	$authAdapter->setTableName('users')
    				->setIdentityColumn('username')
    				->setCredentialColumn('password');
    	return $authAdapter;
    }


}



